<?php
/**
 * Created by PhpStorm.
 * User: LHG
 * Date: 2019/4/15
 * Time: 11:30
 */

namespace hg;
use think\facade\Config;
use think\exception\HttpResponseException;
use think\Response;
use hg\Code;

class ServerResponse
{
    public function __construct($status,$msg = "",$data = [])
    {

        $result['StatusCode'] = $status;
        $msg ? $result['message'] = $msg : null;
        $result['data'] = $data;

        $type                                   = $this->getResponseType();
        $header['Access-Control-Allow-Origin']  = '*';
        $header['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type';
        $header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS';
        $response                               = Response::create($result, $type)->header($header);
        throw  new HttpResponseException($response);
    }


    /**
     * 接口返回信息
     * @param int $code  状态码
     * @param array $data 数据
     * @return ServerResponse
     */
    public static function  message($code = 20000,$msg = '',$data = []){
        $code_arr = Code::CODE_ARRAY;
        if(!$msg){
            $msg = $code_arr[$code]['msg'];
        }
        $successCodeMsg = $msg;

        return new ServerResponse($code, $successCodeMsg,$data);
    }

    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    private function getResponseType()
    {
        return Config::get('default_ajax_return');
    }
}